package com.bonana.bozone.controller;

import com.bonana.core.utils.FileInfo;
import com.bonana.core.utils.ImageScaleUtil;
import com.bonana.core.utils.OssUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created by justin on 15/9/3.
 */
@Controller
@RequestMapping("commons")
public class CommonController {
    @Autowired
    HttpServletRequest request;

    @Autowired
    ServletContext servletContext;

    @ResponseBody
    @RequestMapping("upload")
    public FileInfo uploadFile(@RequestParam(required = false, defaultValue = "0") Integer thumbnail, MultipartFile file) {
        if (file==null) {
            return null;
        }
        FileInfo fileInfo =  OssUtils.putFile(file);
        if(thumbnail == 1) {
            try {
                String fileSuffix = OssUtils.getSuffixByFilename(file.getOriginalFilename());
                fileInfo.setThumbnailUrl(ImageScaleUtil.resizeImage(file.getInputStream(), fileSuffix, 360, 360));
            } catch (IOException e) {
                fileInfo.setThumbnailUrl(fileInfo.getUrl());
                e.printStackTrace();
            }
        }
        return fileInfo;
    }
}
